package dth.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import dth.entity.Dealer;
import dth.entity.Faq;
import dth.entity.Package;
import dth.entity.User;

public class DealerDAO {
	private SessionFactory sessionFactory = new AnnotationConfiguration()
			.configure().buildSessionFactory();
	private Session session = sessionFactory.openSession();

	public java.util.List<Dealer> getListDealer() {
		session.beginTransaction();
		String queryString = "select * from dealer";
		Query query = session.createSQLQuery(queryString).addEntity(
				Dealer.class);
		return query.list();
	}

	public int insert(Dealer dealer) {
		Transaction tx = session.beginTransaction();
		String queryString = "INSERT into dealer VALUES(0,:name,:date_insert,:address)";
		System.out.println("-----INSERT into dealer VALUES(0,"
				+ dealer.getDealerName() + "," + dealer.getDateInsert() + ","
				+ dealer.getDealerAddress());
		Query query = session.createSQLQuery(queryString);
		query.setParameter("name", dealer.getDealerName());
		query.setParameter("date_insert", dealer.getDateInsert());
		query.setParameter("address", dealer.getDealerAddress());
		int count = query.executeUpdate();
		tx.commit();
		return count;
	}

	public int update(Dealer dealer) {
		Transaction tx = session.beginTransaction();
		String queryString = "update dealer set dealer_name=:name,date_insert=:date_insert,address=:address where dealer_id=:id";
		Query query = session.createSQLQuery(queryString);
		query.setParameter("id", dealer.getDealerId());
		query.setParameter("name", dealer.getDealerName());
		query.setParameter("date_insert", dealer.getDateInsert());
		query.setParameter("address", dealer.getDealerAddress());
		int count = query.executeUpdate();
		tx.commit();
		return count;
	}

	public int delete(int id) {
		Transaction tx = session.beginTransaction();
		String queryString = "delete from dealer where dealer_id= :id";
		Query query = session.createSQLQuery(queryString)
				.setParameter("id", id);
		int count = query.executeUpdate();
		tx.commit();
		return count;
	}
	public List<Dealer> getDealerByID(int dealerId){
		String queryString="select * from dealer where dealer_id=:id";
		Query query=session.createSQLQuery(queryString).addEntity(Dealer.class);
		query.setParameter("id",dealerId);
		List<Dealer> dealers=query.list();
		return dealers;
	}
}